package com.mbc.rmt.manager;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

import com.mbc.common.CommonSingleton;
import com.mbc.common.dao.CommonDAOFactory;
import com.mbc.common.dao.CurrencyRateDAO;
import com.mbc.common.dao.CurrencyRateDetailDAO;
import com.mbc.common.dao.LogDAO;
import com.mbc.common.entities.CurrencyRate;
import com.mbc.common.entities.CurrencyRateDetail;
import com.mbc.common.entities.Log;
import com.mbc.common.exception.DataDuplicationException;
import com.mbc.common.manager.AbstractMgr;
import com.mbc.common.utils.KeyGenerator;
import com.mbc.rmt.dao.AgentBalanceDAO;
import com.mbc.rmt.dao.AgentCOADAO;
import com.mbc.rmt.dao.AgentDAO;
import com.mbc.rmt.dao.BankDAO;
import com.mbc.rmt.dao.CashPaymentByReturnDAO;
import com.mbc.rmt.dao.CashPaymentDetailDAO;
import com.mbc.rmt.dao.General_COADAO;
import com.mbc.rmt.dao.OfficeCOADAO;
import com.mbc.rmt.dao.RemittanceDAOFactory;
import com.mbc.rmt.dao.SentCOADAO;
import com.mbc.rmt.dao.WaitingCOADAO;
import com.mbc.rmt.data.CashPaymentByReturnDataList;
import com.mbc.rmt.entities.Agent;
import com.mbc.rmt.entities.AgentBalance;
import com.mbc.rmt.entities.AgentCOA;
import com.mbc.rmt.entities.Bank;
import com.mbc.rmt.entities.CashPaymentByReturn;
import com.mbc.rmt.entities.CashPaymentByReturnRpt;
import com.mbc.rmt.entities.DefinePaymentTypeDetail;
import com.mbc.rmt.entities.GeneralLedger;
import com.mbc.rmt.entities.General_COA;
import com.mbc.rmt.entities.OfficeCOA;
import com.mbc.rmt.entities.SentCOA;
import com.mbc.rmt.entities.WaitingCOA;
import com.mbc.rmt.manager.SavingMgr.GL_STATUS;

public class CashPaymentByReturnMgr extends AbstractMgr{
	
	private CashPaymentByReturnDAO cashpaymentbyreturnDao;
	private CurrencyRateDetailDAO currencyrateDetailDAO;
	private CashPaymentDetailDAO cashpaymentdetaildao;
	private AgentBalanceDAO agentbalanceDAO;
	private CurrencyRateDAO currencyRateDAO;
	private WaitingCOADAO waitingCOADAO;
	private OfficeCOADAO officeCOADAO;
	private SentCOADAO sendCOADAO;
	private General_COADAO generalCOADAO;
	private AgentCOADAO agentCOADAO;
	private AgentDAO agentDAO;
	private BankDAO bankDAO;
	private LogDAO logDAO;
	
	public static enum STATUS { ADD, UPDATE, DELETE }
	public CashPaymentByReturnMgr() {
	}

	public CashPaymentByReturnMgr(String sessionId) {
		this.sessionId = sessionId;
	}
	
	public String create(CashPaymentByReturn entity) throws Exception {
		openConnection();
		try {
			beginTransaction();
			cashpaymentbyreturnDao = RemittanceDAOFactory.getCashPaymentByReturnDAO(dbManager.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			Log l_logentity = new Log();
			String voucher = "";
			if(entity.getSlipid() == 0){
				CashPaymentByReturn l_info = new CashPaymentByReturn();
				l_info = cashpaymentbyreturnDao.find(entity.getSlipid());			
				if (l_info != null) {
					throw new Exception("Invoice ID already exists!");
				} 
				else 
				{			
					if(entity.getAgentid() != null)
						GoToAgentBalance(STATUS.ADD, entity);
					UpdateCurrencyRate(entity);
					UpdateDefinePaymentTypeDetail(STATUS.ADD, entity);
					UpdateCashReturnDetail(STATUS.ADD,entity);
					
					voucher = RemittanceSerialMgr.getFormattedSerial(RemittanceSerialMgr.CASH_PAYMENT_BY_RETURN, entity.getSlipdate(), entity.getBranchid(), getConnection());
					entity.setSlipid(KeyGenerator.generateKey(getConnection()));
					entity.setSlipno(voucher);
					
					gotoGL(entity, GL_STATUS.CREATE);
					cashpaymentbyreturnDao.create(entity);
					
					l_logentity.setTablename("CashPaymentByReturn");
					l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
					l_logentity.setKey(entity.getSlipid());
					l_logentity.setUserid(entity.getCreatedby());
					l_logentity.setLogstatus(Log.__SAVE_DATA);
					logDAO.getData(l_logentity);
				}
			}
			else{
				if(entity.getAgentid() != null)
					GoToAgentBalance(STATUS.UPDATE, entity);
				UpdateCurrencyRate(entity);
				UpdateDefinePaymentTypeDetail(STATUS.UPDATE, entity);
				UpdateCashReturnDetail(STATUS.UPDATE,entity);
				
				cashpaymentbyreturnDao = RemittanceDAOFactory.getCashPaymentByReturnDAO(dbManager.getConnection());
				gotoGL(entity, GL_STATUS.CREATE);
				cashpaymentbyreturnDao.update(entity);
				
				l_logentity.setTablename("CashPaymentByReturn");
				l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
				l_logentity.setKey(entity.getSlipid());
				l_logentity.setUserid(entity.getModifiedby());
				l_logentity.setLogstatus(Log.__UPDATE_DATA);
				logDAO.getData(l_logentity);
			}
			commintTransaction();
			return voucher;
		} catch (SQLException e) {
			if (DataDuplicationException.UNIQUE_KEY_ERROR_CODE == e
					.getErrorCode())
				throw new DataDuplicationException(e.getMessage());
			else
				rollbackTransaction();
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public void delete(CashPaymentByReturn entity,long userId, Date deletedDate) throws Exception {
		openConnection();
		try {
			cashpaymentbyreturnDao = RemittanceDAOFactory.getCashPaymentByReturnDAO(dbManager
					.getConnection());
//			agentbalanceDAO = RemittanceDAOFactory.getAgentBalanceDAO(dbManager
//					.getConnection());
			logDAO = CommonDAOFactory.getLogDAO(getConnection());
			Log l_logentity = new Log();
			l_logentity.setTablename("CashPaymentByReturn");
			l_logentity.setLogkey(KeyGenerator.generateKey(getConnection()));
			l_logentity.setKey(entity.getSlipid());
			l_logentity.setUserid(userId);
			l_logentity.setLogstatus(Log.__DELETE_DATA);
			logDAO.getData(l_logentity);
			
			if(entity.getAgentid() != null)
				GoToAgentBalance(STATUS.DELETE, entity);
			UpdateDefinePaymentTypeDetail(STATUS.DELETE, entity);
			UpdateCashReturnDetail(STATUS.DELETE,entity);
			gotoGL(entity, GL_STATUS.DELETE);
			cashpaymentbyreturnDao.delete(entity);
			
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public CashPaymentByReturnDataList findCashPaymentByReturn(CashPaymentByReturn cri)
			throws Exception {
		openConnection();
		try {
			cashpaymentbyreturnDao = RemittanceDAOFactory.getCashPaymentByReturnDAO(dbManager
					.getConnection());
			return cashpaymentbyreturnDao.findCashPaymentByReturn(cri);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public CashPaymentByReturnDataList findCashReturnDetaillist(CashPaymentByReturn cri)
			throws Exception {
		openConnection();
		try {
			cashpaymentbyreturnDao = RemittanceDAOFactory.getCashPaymentByReturnDAO(dbManager
					.getConnection());
			return cashpaymentbyreturnDao.findCashReturnDetaillist(cri);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public CashPaymentByReturn getCashPaymentByReturn(CashPaymentByReturn saving) throws Exception {
		openConnection();
		try {
			cashpaymentbyreturnDao = RemittanceDAOFactory.getCashPaymentByReturnDAO(dbManager
					.getConnection());
			return cashpaymentbyreturnDao.getCashPaymentByReturn(saving);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public void GoToAgentBalance(STATUS Status,CashPaymentByReturn  entity) throws Exception {
		try {
			agentbalanceDAO = RemittanceDAOFactory.getAgentBalanceDAO(dbManager
					.getConnection());
			AgentBalance l_agent = new AgentBalance();
			if(Status == STATUS.ADD){
				l_agent = new AgentBalance();
				l_agent.setAgent_id(entity.getAgentid());
				l_agent.setCurrencyid(entity.getCurrencyid());
				l_agent = agentbalanceDAO.getInfo(l_agent);
				if(l_agent == null)
				{
					l_agent = new AgentBalance();
					l_agent.setAgentbalance_id(KeyGenerator.generateKey(getConnection()));
					l_agent.setAgent_id(entity.getAgentid());
					l_agent.setCurrencyid(entity.getCurrencyid());
					l_agent.setCurrentbalance(entity.getAmount());
					agentbalanceDAO.create(l_agent);
				}
				else
				{
					l_agent.setCurrentbalance(l_agent.getCurrentbalance()+entity.getAmount());
					agentbalanceDAO.update(l_agent);
				}
			}
			else if(Status == STATUS.UPDATE)
			{
				l_agent = new AgentBalance();
				double amt = 0;
				double tempamt = 0;
				CashPaymentByReturn tempentity = new CashPaymentByReturn();
				tempentity = cashpaymentbyreturnDao.find(entity.getSlipid());
				amt = entity.getAmount();
				tempamt = tempentity.getAmount();
				long currencyid= entity.getCurrencyid();
				long tempcur = tempentity.getCurrencyid();
				long agent = entity.getAgentid();
				long tempagent = tempentity.getAgentid();
				
				if(tempcur == currencyid && tempagent == agent)
						{
							l_agent.setAgent_id(entity.getAgentid());
							l_agent.setCurrencyid(entity.getCurrencyid());	
							l_agent = agentbalanceDAO.getInfo(l_agent);
							l_agent.setCurrentbalance((l_agent.getCurrentbalance()-tempamt) + amt);
						}
						else
						{
							double amount = 0;
							l_agent.setCurrencyid(tempcur);
							l_agent.setAgent_id(tempagent);
							l_agent = agentbalanceDAO.getInfo(l_agent);
							amount = l_agent.getCurrentbalance() - tempamt;						
							l_agent.setCurrentbalance(amount);
							agentbalanceDAO.update(l_agent);			
							
							l_agent.setAgent_id(entity.getAgentid());
							l_agent.setCurrencyid(entity.getCurrencyid());	
							l_agent = agentbalanceDAO.getInfo(l_agent);
							if(l_agent == null)
							{
								l_agent = new AgentBalance();
								l_agent.setAgentbalance_id(KeyGenerator.generateKey(getConnection()));
								l_agent.setAgent_id(entity.getAgentid());
								l_agent.setCurrencyid(entity.getCurrencyid());
								l_agent.setOpeningbalance(0);
								l_agent.setCurrentbalance(amt);
								agentbalanceDAO.create(l_agent);
							}
							else
							{
								if(currencyid == tempcur && agent == tempagent)
										l_agent.setCurrentbalance(amount+amt);
								else
										l_agent.setCurrentbalance(l_agent.getCurrentbalance() + amt);
							}
						}
						agentbalanceDAO.update(l_agent);
			}
			else
			{
				l_agent = new AgentBalance();
				l_agent.setCurrencyid(entity.getCurrencyid());
				l_agent.setAgent_id(entity.getAgentid());
				l_agent = agentbalanceDAO.getInfo(l_agent);
				if(l_agent != null)
				{
					l_agent.setAgent_id(entity.getAgentid());
					l_agent.setCurrencyid(entity.getCurrencyid());
					l_agent.setCurrentbalance(l_agent.getCurrentbalance()-entity.getAmount());					
					agentbalanceDAO.update(l_agent);
				}
			}
		} catch(Exception e) { throw e; }
		/* -- END GL ADD DATA -- */
	} 
	
	public void UpdateCurrencyRate(CashPaymentByReturn  entity) throws Exception {
		try {
			currencyrateDetailDAO = CommonDAOFactory.getCurrencyRateDetailDAO(dbManager.getConnection());
			
			CurrencyRateDetail l_currencyrateDetail = new CurrencyRateDetail();					
			l_currencyrateDetail = currencyrateDetailDAO.findLatest(entity.getCurrencyrateid());
			
			if (l_currencyrateDetail.getRate()  !=  entity.getRate()){					  
		   
			   l_currencyrateDetail.setCurrencyRateDetailId(KeyGenerator.generateKey(getConnection()));
			   l_currencyrateDetail.setCurrencyRateId(entity.getCurrencyrateid());
			   l_currencyrateDetail.setRate(entity.getRate());
			   l_currencyrateDetail.seteDateTime(entity.getSlipdate());
			   currencyrateDetailDAO.create(l_currencyrateDetail);
			}
		} catch(Exception e) { throw e; }
		/* -- END GL ADD DATA -- */
	} 
	
	public void UpdateDefinePaymentTypeDetail(STATUS Status,CashPaymentByReturn  entity) throws Exception {
		try {
			DefinePaymentTypeDetail l_dptdetail = new DefinePaymentTypeDetail();
			cashpaymentdetaildao = RemittanceDAOFactory.getCashPaymentDetailDAO(dbManager.getConnection());
			if(Status == STATUS.ADD){
				l_dptdetail = new DefinePaymentTypeDetail();
				l_dptdetail.setPaidamount(cashpaymentdetaildao.finddefinepaidamt(entity.getDefinedetailid()).getPaidedamount());
				l_dptdetail.setPaidamount(l_dptdetail.getPaidamount() + entity.getAmount());	
				l_dptdetail.setTranStatus((byte)1);
				l_dptdetail.setReturnstatus((byte)0);
				l_dptdetail.setDetailId(entity.getDefinedetailid());
				cashpaymentdetaildao.updateTranStatusDPD(l_dptdetail);
			}
			
			else if(Status == STATUS.UPDATE){
				
				l_dptdetail = new DefinePaymentTypeDetail();
				CashPaymentByReturn l_tempdetail = new CashPaymentByReturn();
				
				l_tempdetail = cashpaymentbyreturnDao.find(entity.getSlipid());
				long tempdptdetailid = 0;
				long dptdetailid =0 ;
				tempdptdetailid = l_tempdetail.getDefinedetailid();
				dptdetailid = entity.getDefinedetailid();						
				
				if(tempdptdetailid != dptdetailid ){						
					l_dptdetail.setPaidamount(cashpaymentdetaildao.finddefinepaidamt(l_tempdetail.getDefinedetailid()).getPaidedamount());
					l_dptdetail.setPaidamount(l_dptdetail.getPaidamount()-l_tempdetail.getAmount());
					if(l_dptdetail.getPaidamount() == 0)
						l_dptdetail.setTranStatus((byte)0);
					else
						l_dptdetail.setTranStatus((byte)1);
					l_dptdetail.setReturnstatus((byte)1);
					
					l_dptdetail.setDetailId(l_tempdetail.getDefinedetailid());
					cashpaymentdetaildao.updateTranStatusDPD(l_dptdetail);
					
					l_dptdetail = new DefinePaymentTypeDetail();
					l_dptdetail.setPaidamount(cashpaymentdetaildao.finddefinepaidamt(entity.getDefinedetailid()).getPaidedamount());
					l_dptdetail.setPaidamount(l_dptdetail.getPaidamount() +entity.getAmount());	
					l_dptdetail.setTranStatus((byte)1);
					l_dptdetail.setReturnstatus((byte)0);
					l_dptdetail.setDetailId(entity.getDefinedetailid());
					cashpaymentdetaildao.updateTranStatusDPD(l_dptdetail);
				}
				else{
					l_dptdetail = new DefinePaymentTypeDetail();
					l_dptdetail.setPaidamount(cashpaymentdetaildao.finddefinepaidamt(entity.getDefinedetailid()).getPaidedamount());
					l_dptdetail.setPaidamount((l_dptdetail.getPaidamount()-l_tempdetail.getAmount()) + entity.getAmount());	
					l_dptdetail.setTranStatus((byte)1);
					l_dptdetail.setReturnstatus((byte)0);
					l_dptdetail.setDetailId(entity.getDefinedetailid());
					cashpaymentdetaildao.updateTranStatusDPD(l_dptdetail);
				}
			}
			else{
				l_dptdetail = new DefinePaymentTypeDetail();
				
				cashpaymentdetaildao.finddefinepaidamt(entity.getDefinedetailid());
				
				l_dptdetail.setPaidamount(cashpaymentdetaildao.finddefinepaidamt(entity.getDefinedetailid()).getPaidedamount());
				l_dptdetail.setPaidamount(l_dptdetail.getPaidamount() - entity.getAmount());
				if(l_dptdetail.getPaidamount() == 0)
					l_dptdetail.setTranStatus((byte)0);
				else
					l_dptdetail.setTranStatus((byte)1);
				l_dptdetail.setReturnstatus((byte)1);
				l_dptdetail.setDetailId(entity.getDefinedetailid());
				cashpaymentdetaildao.updateTranStatusDPD(l_dptdetail);
			}
				
		} catch(Exception e) { throw e; }
		/* -- END GL ADD DATA -- */
	} 
	
	public void UpdateCashReturnDetail(STATUS Status,CashPaymentByReturn  entity) throws Exception {
		try {
			CashPaymentByReturn l_preturn = new CashPaymentByReturn();
			cashpaymentdetaildao = RemittanceDAOFactory.getCashPaymentDetailDAO(dbManager.getConnection());
			if(Status == STATUS.ADD){
				l_preturn = new CashPaymentByReturn();
				
				l_preturn.setPaidamount(cashpaymentbyreturnDao.findpaidamt(entity.getReturndetailid()).getPaidamount());
				l_preturn.setPaidamount(l_preturn.getPaidamount() + entity.getAmount());	
				l_preturn.setP_returnstatus((byte)1);
				l_preturn.setReturndetailid(entity.getReturndetailid());
				cashpaymentbyreturnDao.updateCashReturn(l_preturn);
			}
			
			else if(Status == STATUS.UPDATE){
				
				l_preturn = new CashPaymentByReturn();
				CashPaymentByReturn l_tempdetail = new CashPaymentByReturn();
				
				l_tempdetail = cashpaymentbyreturnDao.find(entity.getSlipid());
				long tempreturndetailid = 0;
				long returndetailid =0 ;
				tempreturndetailid = l_tempdetail.getReturndetailid();
				returndetailid = entity.getReturndetailid();						
				
				if(tempreturndetailid != returndetailid ){			
					l_preturn.setPaidamount(cashpaymentbyreturnDao.findpaidamt(l_tempdetail.getReturndetailid()).getPaidamount());
					l_preturn.setPaidamount(l_preturn.getPaidamount()-l_tempdetail.getAmount());				
					l_preturn.setP_returnstatus((byte)0);					
					l_preturn.setReturndetailid(l_tempdetail.getReturndetailid());
					cashpaymentbyreturnDao.updateCashReturn(l_preturn);
					
					l_preturn = new CashPaymentByReturn();
					l_preturn.setPaidamount(cashpaymentbyreturnDao.findpaidamt(entity.getReturndetailid()).getPaidamount());
					l_preturn.setPaidamount(l_preturn.getPaidamount() +entity.getAmount());	
					l_preturn.setP_returnstatus((byte)1);
					l_preturn.setReturndetailid(entity.getReturndetailid());
					cashpaymentbyreturnDao.updateCashReturn(l_preturn);
				}
				else{
					l_preturn = new CashPaymentByReturn();
					l_preturn.setPaidamount(cashpaymentbyreturnDao.findpaidamt(entity.getReturndetailid()).getPaidamount());
					l_preturn.setPaidamount((l_preturn.getPaidamount()-l_tempdetail.getAmount()) + entity.getAmount());	
					l_preturn.setP_returnstatus((byte)1);
					l_preturn.setReturndetailid(entity.getReturndetailid());
					cashpaymentbyreturnDao.updateCashReturn(l_preturn);
				}
			}
			else{
				l_preturn = new CashPaymentByReturn();				
				l_preturn.setPaidamount(cashpaymentbyreturnDao.findpaidamt(entity.getReturndetailid()).getPaidamount());
				l_preturn.setPaidamount(l_preturn.getPaidamount() - entity.getAmount());
				l_preturn.setP_returnstatus((byte)0);
				l_preturn.setReturndetailid(entity.getReturndetailid());
				cashpaymentbyreturnDao.updateCashReturn(l_preturn);
			}
				
		} catch(Exception e) { throw e; }
		/* -- END GL ADD DATA -- */
	} 
	
	//Report
		public JasperPrint prepareCashPaymentByReturnReport(CashPaymentByReturnRpt info)
				throws Exception {
			openConnection();
			JasperPrint l_jsPrint = null;
			try {
				cashpaymentbyreturnDao = RemittanceDAOFactory.getCashPaymentByReturnDAO(dbManager.getConnection());
				JRResultSetDataSource l_jrRS = new JRResultSetDataSource(cashpaymentbyreturnDao.prepareCashPaymentByReturnReport(info));
				JasperReport l_jsRpt = null;
				if(info.getGroupby().equals("CurrencyID"))
					l_jsRpt = (JasperReport) JRLoader
					.loadObjectFromFile(CommonSingleton.ABSOLUTE_PATH +"reports/CashPaymentByReturnforCurRpt.jasper");							
				else
					l_jsRpt = (JasperReport) JRLoader
						.loadObjectFromFile(CommonSingleton.ABSOLUTE_PATH +"reports/CashPaymentByReturnRpt.jasper");
		
				HashMap<String, Object> l_params = new HashMap<String, Object>();
				l_params.put("companyname", "mbc");
				l_jsPrint = JasperFillManager.fillReport(l_jsRpt, l_params, l_jrRS);

			} catch (JRException je) {
				throw je;
			} catch (Exception e) {
				throw e;
			} finally {
				closeConnection();
			}

			return l_jsPrint;

		}
		
		public void gotoGL(CashPaymentByReturn l_entity, GL_STATUS status) throws Exception {
			
			currencyRateDAO = CommonDAOFactory.getCurrencyRateDAO(getConnection());
			officeCOADAO = RemittanceDAOFactory.getOfficeCOADAO(getConnection());
			waitingCOADAO = RemittanceDAOFactory.getWaitingCOADAO(getConnection());
			sendCOADAO = RemittanceDAOFactory.getSentCOADAO(getConnection());
			generalCOADAO = RemittanceDAOFactory.getGeneral_COADAO(getConnection());
			bankDAO = RemittanceDAOFactory.getBankDAO(getConnection());
			agentCOADAO = RemittanceDAOFactory.getAgentCOADAO(getConnection());
			agentDAO = RemittanceDAOFactory.getAgentDAO(getConnection());
			
			//BranchCOA l_branchCOA = branchCOADAO.findByHostBranchID(l_entity.getBranchId(), l_entity.getBranchId());
			
			//if(l_branchCOA == null)
				//throw new DataNotFoundException("Plz fill BranchCOA");
			
			GeneralLedgerMgr l_glmgr = new GeneralLedgerMgr(this.sessionId);
			
			if(status == GL_STATUS.DELETE)
					l_glmgr.deleteGL(l_entity.getSlipno() + "-PR");
			
			l_glmgr.deleteGL(l_entity.getSlipno() + "-PR");
			
			if(status == GL_STATUS.CREATE) {
				GeneralLedger _glHeader = new GeneralLedger();
//				_glHeader.setGlKey(KeyGenerator.generateKey(getConnection()));
				_glHeader.setGlKey(l_glmgr.getGLKey());
				_glHeader.setSlip_ID(l_entity.getSlipno() + "-PR");
				_glHeader.setSlipDate(l_entity.getSlipdate());
				_glHeader.setSystemDate(new Date());
				_glHeader.setStatus("JH");
				_glHeader.setSrNo(1);
				_glHeader.setOffice_ID(l_entity.getBranchid());
				
//				for(int i = 0; i < l_entity.getL_detail().size(); i++) {
					
					CurrencyRate l_currencyrate = currencyRateDAO.getCurrencyRateFromSourcetoHome(l_entity.getCurrencyid(), l_entity.getBranchid());
					
					if(!l_entity.getTypecode().equals("A") && !l_entity.getTypecode().equals("B")) {
						
						GeneralLedger _glDedit = new GeneralLedger();
//						_glDedit.setGlKey(KeyGenerator.generateKey(getConnection()));
						_glDedit.setGlKey(l_glmgr.getGLKey());
						_glDedit.setSlip_ID(l_entity.getSlipno() + "-PR");
						_glDedit.setSlipDate(l_entity.getSlipdate());
						_glDedit.setSystemDate(new Date());
						
						if(l_entity.getTypecode().equals("O")) {
							OfficeCOA l_officecoa = officeCOADAO.findByCode("O", l_entity.getBranchid());
							_glDedit.setCoaKey(l_officecoa.getAccpayable());
							_glDedit.setDepartmentKey(l_officecoa.getAccpayable_dept());
						} else if(l_entity.getTypecode().equals("W")){
							WaitingCOA l_waitingcoa = waitingCOADAO.findByCode("W", l_entity.getBranchid());
							_glDedit.setCoaKey(l_waitingcoa.getAccpayable());
							_glDedit.setDepartmentKey(l_waitingcoa.getAccpayable_dept());
						} else if(l_entity.getTypecode().equals("S")) {
							SentCOA l_sendcoa = sendCOADAO.findByCode("S", l_entity.getBranchid());
							_glDedit.setCoaKey(l_sendcoa.getAccpayable());
							_glDedit.setDepartmentKey(l_sendcoa.getAccpayable_dept());
						}
						
						_glDedit.setCurrencyKey(l_entity.getCurrencyid());
						_glDedit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
						_glDedit.setExchangeRate(l_currencyrate.getRate());
						_glDedit.setSourceAmount((l_entity.getAmount()));
						
						if(l_currencyrate.getRoper().equals("M"))
							_glDedit.setHomeAmount((l_entity.getAmount() * l_currencyrate.getRate()));
						else
							_glDedit.setHomeAmount((l_entity.getAmount() / l_currencyrate.getRate()));
						
						_glDedit.setStatus("JPR");
						_glDedit.setSrNo((1));
						_glDedit.setOffice_ID(l_entity.getBranchid());
						
						l_glmgr.createGL(_glDedit);
					}else{
						
						Agent l_agent = agentDAO.findByCode(l_entity.getAgentcode(),l_entity.getBranchid());
						AgentCOA l_agentCOA = agentCOADAO.findByCode(l_agent.getAccountset_code(),l_entity.getBranchid());
							
						Bank l_Bank = new Bank();
						if(l_entity.getBankid() != null){
							l_Bank = bankDAO.findByCode(l_entity.getBankcode(),l_entity.getBranchid());
						}
						
						GeneralLedger _glDebit = new GeneralLedger();
//						_glDebit.setGlKey(KeyGenerator.generateKey(getConnection()));
						_glDebit.setGlKey(l_glmgr.getGLKey());
						_glDebit.setSlip_ID(l_entity.getSlipno() + "-PR");
						_glDebit.setSlipDate(l_entity.getSlipdate());
						_glDebit.setSystemDate(new Date());
						if(l_entity.getBankid() == null){
							_glDebit.setCoaKey(l_agentCOA.getAccpayable());
							_glDebit.setDepartmentKey(l_agentCOA.getAccpayable_dept());
						}else{
							_glDebit.setCoaKey(l_Bank.getCoaid());
							_glDebit.setDepartmentKey(l_Bank.getDepartmentid());
						}
						_glDebit.setCurrencyKey(l_entity.getCurrencyid());
						_glDebit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
						_glDebit.setExchangeRate(l_currencyrate.getRate());
						_glDebit.setSourceAmount(l_entity.getAmount());
						
						if(l_currencyrate.getRoper().equals("M"))
							_glDebit.setHomeAmount(l_entity.getAmount() * l_currencyrate.getRate());
						else
							_glDebit.setHomeAmount(l_entity.getAmount() / l_currencyrate.getRate());
						
						_glDebit.setStatus("JPA");
						_glDebit.setSrNo(1);
						_glDebit.setOffice_ID(l_entity.getBranchid());						
						l_glmgr.createGL(_glDebit);							
					}					
				
						General_COA l_generalCOA = generalCOADAO.find(l_entity.getBranchid());
						Bank l_Bank = new Bank();
						if(l_entity.getBankid() != null){
							l_Bank = bankDAO.findByCode(l_entity.getBankcode(), l_entity.getBranchid());
						}
						GeneralLedger _glCredit = new GeneralLedger();
//						_glCredit.setGlKey(KeyGenerator.generateKey(getConnection()));	
						_glCredit.setGlKey(l_glmgr.getGLKey());
						_glCredit.setSlip_ID(l_entity.getSlipno() + "-PR");
						_glCredit.setSlipDate(l_entity.getSlipdate());
						_glCredit.setSystemDate(new Date());
						if(l_entity.getBankid() == null){
							_glCredit.setCoaKey(l_generalCOA.getCashAccountID());
							_glCredit.setDepartmentKey(l_generalCOA.getCashDepartmentID());
						}else{
							_glCredit.setCoaKey(l_Bank.getCoaid());
							_glCredit.setDepartmentKey(l_Bank.getDepartmentid());
						}
						_glCredit.setCurrencyKey(l_entity.getCurrencyid());
						_glCredit.setCurrencyRateKey(l_currencyrate.getCurrencyRateId());
						_glCredit.setExchangeRate(l_currencyrate.getRate());
						_glCredit.setSourceAmount(-l_entity.getAmount());
						
						if(l_currencyrate.getRoper().equals("M"))
							_glCredit.setHomeAmount(-(l_entity.getAmount()) * l_currencyrate.getRate());
						else
							_glCredit.setHomeAmount(-(l_entity.getAmount() / l_currencyrate.getRate()));
						
						_glCredit.setStatus("JPR");	
						_glCredit.setSrNo(2);
						_glCredit.setOffice_ID(l_entity.getBranchid());			
						l_glmgr.createGL(_glCredit);		
					
//				}					
				l_glmgr.createGL(_glHeader);
			}
		}
}
